<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="书名"
        style="width: 200px;margin-left: 10px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
      />
      <el-input
        v-model="listQuery.author"
        placeholder="作者"
        style="width: 200px;margin-left: 10px;"
        class="filter-item"
        clearable
        @keyup.enter.native="handleFilter"
        @clear="handleFilter"
      />
      <el-select
        style="margin-left: 10px;"
        v-model="listQuery.category"
        placeholder="分类"
        clearable
        class="filter-item"
      >
        <!--    el-select     @change="handleFilter" -->
        <el-option
          v-for="item in categoryList"
          :key="item.value"
          :label="`${item.label}(${item.num})`"
          :value="item.label"
        />
      </el-select>
      <el-button
        style="margin-left: 15px;"
        v-waves
        class="filter-item"
        type="primary"
        @click="handleFilter"
        icon="el-icon-search"
        >查询</el-button
      >
      <el-button
        style="margin-left: 10px;"
        v-waves
        class="filter-item"
        type="primary"
        @click="handleCreate"
        icon="el-icon-edit"
        >新增</el-button
      >
      <el-checkbox
        v-model="showCover"
        class="filter-item"
        style="margin-left: 10px;"
        @change="changeShowCover"
      >
        显示封面
      </el-checkbox>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      :defaultSort="defaultSort"
      @sort-change="sortChange"
    >
      <el-table-column
        lable="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
      ></el-table-column>
      <el-table-column label="书名" align="center" :width="150">
        <template v-slot="{ row: { titleWrapper } }">
          <!-- <template slot-scope="{row:{title}}"> -->
          <!-- <span>{{title}}</span> -->
          <span v-html="titleWrapper"></span>
        </template>
      </el-table-column>
      <el-table-column label="作者" align="center" :width="150">
        <template v-slot="{ row: { authorWrapper } }">
          <span v-html="authorWrapper"></span>
        </template>
      </el-table-column>
      <el-table-column
        label="出版社"
        align="center"
        :width="150"
        prop="publisher"
      />
      <el-table-column
        label="分类"
        align="center"
        :width="100"
        prop="categoryText"
      />
      <el-table-column label="语言" align="center" prop="language" />
      <el-table-column v-if="showCover" label="封面" align="center" width="150">
        <template v-slot="{ row: { cover } }">
          <a href="cover" target="_blank">
            <img :src="cover" style="width: 120px;height: 180px;" />
          </a>
        </template>
      </el-table-column>
      <el-table-column
        label="文件名"
        align="center"
        prop="fileName"
        width="100"
      />
      <el-table-column
        label="文件路径"
        align="center"
        prop="filePath"
        width="100"
      >
        <template v-slot="{ row: { filePath } }">
          <span>{{ filePath | valueFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="封面路径"
        align="center"
        prop="coverPath"
        width="100"
      >
        <template v-slot="{ row: { coverPath } }">
          <span>{{ coverPath | valueFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="解压路径"
        align="center"
        prop="unziPath"
        width="100"
      >
        <template v-slot="{ row: { unziPath } }">
          <span>{{ unziPath | valueFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="上传人"
        align="center"
        prop="createUser"
        width="100"
      />
      <el-table-column
        label="上传时间"
        align="center"
        prop="createDt"
        width="100"
      >
        <template v-slot="{ row: { createDt } }">
          <span>{{ createDt | timeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" align="center" fixed="right">
        <template v-slot="{ row }">
          <el-button
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
          />
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-if="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="refresh"
    ></Pagination>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import { getCategory, getListBook, deleteBook } from '@/api/book.js'
import { parseTime } from '@/utils'
export default {
  name: 'bookList',
  components: {
    Pagination
  },
  directives: { waves },
  filters: {
    valueFilter(value) {
      return value || '无'
    },
    timeFilter(value) {
      if (value) {
        // const now = new Date(value)
        // let year = now.getFullYear()
        //   let month = now.getMonth() + 1 //真实的月份需要再加上1
        //   let day = now.getDate()
        //   let h = now.getHours()
        //   let m = now.getMinutes()
        //   let s = now.getSeconds()
        //   return `${year}-${month > 9 ? month : '0' + month}-${day > 9 ? day : '0' + day} ${h > 9 ? h : '0' + h}:${
        //         m > 9 ? m : '0' + m
        //       }:${s > 9 ? s : '0' + s}`
        return parseTime(value)
      } else {
        return '无'
      }
    }
  },
  props: {},
  data() {
    return {
      listQuery: {},
      showCover: false,
      categoryList: [],
      tableKey: 0,
      listLoading: true,
      list: [],
      total: 0,
      defaultSort: {}
    }
  },
  methods: {
    handleDelete(item) {
      this.$confirm('此操作将永久删除该电子书，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBook({
          fileName: item.fileName
        }).then(res => {
          console.log(res)
          this.$message({
            message: res.msg || '删除成功',
            type: 'success'
          })
          this.getList()
        })
      })
    },
    parseQuery() {
      const query = { ...this.$route.query }
      let sort = '+id'
      const listQuery = {
        page: 1,
        pageSize: 20,
        sort
      }
      if (query) {
        query.page && (query.page = +query.page)
        query.pageSize && (query.pageSize = +query.pageSize)
        query.sort && (sort = query.sort)
      }
      const sortSymbol = sort[0]
      const sortColumn = sort.slice(1, sort.length)
      this.defaultSort = {
        prop: sortColumn,
        order: sortSymbol === '+' ? 'ascending' : 'descending'
      }
      this.listQuery = { ...listQuery, ...query }
    },
    handleUpdate(row) {
      console.log(row)
      this.$router.push(`/book/edit/${row.fileName}`)
    },
    sortChange(data) {
      const { prop, order } = data
      this.sortBy(prop, order)
    },
    sortBy(prop, order) {
      if (order === 'ascending') {
        // 升序
        this.listQuery.sort = `+${prop}`
      } else {
        // 降序
        this.listQuery.sort = `-${prop}`
      }
      this.handleFilter()
    },
    refresh() {
      this.$router.push({
        path: '/book/list',
        query: this.listQuery
      })
      this.getList()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.refresh()
      // this.getList()
    },
    handleCreate() {
      this.$router.push('/book/create')
    },
    changeShowCover(value) {
      this.showCover = value
    },
    getCategoryList() {
      getCategory().then(res => {
        this.categoryList = res.data
      })
    },
    wrapperKeyword(k, v) {
      function highlight(value) {
        return `<span style="color:#1890ff">${value}</span>`
      }
      if (!this.listQuery[k]) {
        return v
      } else {
        return v.replace(new RegExp(this.listQuery[k], 'ig'), v => highlight(v))
      }
    },
    getList() {
      this.listLoading = true
      getListBook(this.listQuery).then(res => {
        const { total, data, page } = res
        this.list = data
        this.total = total
        this.page = page + 1
        this.listLoading = false
        this.list.forEach(v => {
          v.titleWrapper = this.wrapperKeyword('title', v.title)
          v.authorWrapper = this.wrapperKeyword('author', v.author)
        })
      })
    }
  },
  computed: {},
  watch: {},
  created() {
    this.parseQuery()
    this.getList()
    this.getCategoryList()
  }
}
</script>
<style lang="scss" scoped></style>
